package cn.wowjoy.office.materialmanage.stock;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.MaterialSearchAdapter;
import cn.wowjoy.office.common.adapter.MenuAdapter;
import cn.wowjoy.office.common.adapter.StockMainTypeAdapter;
import cn.wowjoy.office.common.adapter.StockSubTypeAdapter;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.StockListRequest;
import cn.wowjoy.office.data.response.HistoryLogResponse;
import cn.wowjoy.office.data.response.MaterialSearchResponse;
import cn.wowjoy.office.data.response.StockTypeResponse;
import cn.wowjoy.office.data.response.Type;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Sherily on 2017/12/28.
 * Description:
 */

public class MaterialStockViewModel extends NewBaseViewModel {

    @Inject
    ApiService apiService;

    private int startIndex = 0;
    private int pageSize = 10;


    private String storageCode;
    private String usageCode;
    private String searchWords;
    private List<String> ids;

    public MenuAdapter stockType = new MenuAdapter();
    public MenuAdapter materialType = new MenuAdapter();
    public StockMainTypeAdapter mainTypeAdapter = new StockMainTypeAdapter();
    public StockSubTypeAdapter subTypeAdapter = new StockSubTypeAdapter();

    public MaterialSearchAdapter searchAdapter = new MaterialSearchAdapter();
    public LRecyclerViewAdapter adapter = new LRecyclerViewAdapter(searchAdapter);


    MediatorLiveData<PopuModel> menu = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<List<PopuModel>>> stockMenu = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<List<PopuModel>>> usageMenu = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<StockTypeResponse>> typeTree = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<List<MaterialSearchResponse>>> stockList = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<List<String>>> listLiveData = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<String>> clean = new MediatorLiveData<>();

    @Inject
    public MaterialStockViewModel(@NonNull NewMainApplication application) {
        super(application);
        stockType.setmEventListener(this);
        materialType.setmEventListener(this);
        mainTypeAdapter.setmEventHandle(this);
        subTypeAdapter.setmEventHandle(this);
        searchAdapter.setmEventHandle(this);
    }

    @Override
    public void loadData(boolean ref) {
        super.loadData(ref);
        getStockList(ref,ids);
    }

    public void setIds(List<String> ids) {
        this.ids = ids;
    }

    public List<String> getIds() {
        return ids;
    }

    public void setSearchWords(String searchWords) {
        this.searchWords = searchWords;
    }

    public void cleanSearchList(){
        searchAdapter.clean();
    }

    public void setStorageCode(String storageCode) {
        this.storageCode = storageCode;
    }

    public void setUsageCode(String usageCode) {
        this.usageCode = usageCode;
    }

    public MediatorLiveData<LiveDataWrapper<List<MaterialSearchResponse>>> getStockList() {
        return stockList;
    }



    /**
     * 2级分类列表操作改变一级列表
     * @param selected
     * @param mainIndex
     * @param subIndex
     * @param count
     */

    public void selectMain(boolean selected, int mainIndex,int subIndex,int count){
        mainTypeAdapter.selectMain(selected,mainIndex,subIndex,count);
    }

    /**
     * 清空选择内容
     */
    public void clear(){
        mainTypeAdapter.clear();
    }

    /**
     * 全选
     */
    public void initType(){
        mainTypeAdapter.initSelected();
        mainTypeAdapter.notifyItemRangeChanged(0,mainTypeAdapter.getItemCount());
    }

    /**
     * 设置二级分类列表
     * @param types
     * @param mainPosition
     * @param isAll
     * @param count
     */

    public void setSub(List<Type> types,int mainPosition,boolean isAll,int count){
        subTypeAdapter.setTypes(types,mainPosition,isAll,count);
    }



    public void setData(boolean isRefresh, List<MaterialSearchResponse> searchResponse) {
        if (isRefresh) {
            searchAdapter.refresh(searchResponse);
        } else {
            searchAdapter.loadMore(searchResponse);
        }
        adapter.removeFooterView();
        if (!isRefresh && (null == searchResponse || searchResponse.isEmpty() )){
            LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
            View view = inflater.inflate(R.layout.nodata_footview,null,false);
            adapter.addFooterView(view);

        }
        adapter.notifyDataSetChanged();
        refreshComplete();
    }
    public void getStockList(boolean isRefresh,List<String> ids){
        if (isRefresh){
            startIndex = 0;
        } else {
            ++startIndex;
        }
        stockList.setValue(LiveDataWrapper.loading(null));
        if (null != ids && ids.isEmpty())
            ids = null;
        StockListRequest request = new StockListRequest(storageCode,usageCode,searchWords,startIndex,pageSize,ids);
        Disposable disposable = apiService.getStockList(request)
                .flatMap(new ResultDataParse<List<MaterialSearchResponse>>())
                .compose(new RxSchedulerTransformer<List<MaterialSearchResponse>>())
                .subscribe(new Consumer<List<MaterialSearchResponse>>() {
                               @Override
                               public void accept(List<MaterialSearchResponse> stockListResponse) throws Exception {
                                   stockList.setValue(LiveDataWrapper.success(stockListResponse));
                                   setData(isRefresh,stockListResponse);
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                stockList.setValue(LiveDataWrapper.error(throwable,null));

                            }
                        });
        addDisposable(disposable);
    }

    /**
     * 设置目录
     * @param popuModel
     */
    public void sort(PopuModel popuModel){
        menu.setValue(popuModel);
    }

    public void getStock(){
        stockMenu.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getStock()
                .flatMap(new ResultDataParse<List<PopuModel>>())
                .compose(new RxSchedulerTransformer<List<PopuModel>>())
                .subscribe(new Consumer<List<PopuModel>>() {
                               @Override
                               public void accept(List<PopuModel> popuModels) throws Exception {
                                   stockMenu.setValue(LiveDataWrapper.success(popuModels));
                                   popuModels.get(0).setSelected(true);
                                   stockType.setPopuModels(popuModels);
                                   getUsage(popuModels.get(0).getCode());
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                stockMenu.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);

    }
    public void getUsage(String storageCode){
        usageMenu.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getUsage(storageCode)
                .flatMap(new ResultDataParse<List<PopuModel>>())
                .compose(new RxSchedulerTransformer<List<PopuModel>>())
                .subscribe(new Consumer<List<PopuModel>>() {
                               @Override
                               public void accept(List<PopuModel> popuModels) throws Exception {
                                   usageMenu.setValue(LiveDataWrapper.success(popuModels));
                                   popuModels.get(0).setSelected(true);
                                   materialType.setPopuModels(popuModels);
                                   getTypeTree(popuModels.get(0).getCode());
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                usageMenu.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);
    }

    public void getTypeTree(String usageCode){
        typeTree.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getStockType(usageCode,"2")
                .flatMap(new ResultDataParse<StockTypeResponse>())
                .compose(new RxSchedulerTransformer<StockTypeResponse>())
                .subscribe(new Consumer<StockTypeResponse>() {
                               @Override
                               public void accept(StockTypeResponse stockTypeResponse) throws Exception {
                                   typeTree.setValue(LiveDataWrapper.success(stockTypeResponse));
                                   mainTypeAdapter.setTypes(stockTypeResponse.getTrees(),Integer.parseInt(stockTypeResponse.getLeafCount()));
                                   List<Type> sub = stockTypeResponse.getTrees().get(0).getSubType();
                                   int count = sub.size();
                                   subTypeAdapter.setTypes(sub,0,true,count);
                                   subTypeAdapter.setTotalSub(Integer.parseInt(stockTypeResponse.getLeafCount()));
                                   getStockList(true,mainTypeAdapter.getSelectIds());

                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                typeTree.setValue(LiveDataWrapper.error(throwable,null));

                            }
                        });
        addDisposable(disposable);

    }





    private List<String> mockdata(){
        List<String> tags = new ArrayList<>();
        tags.add("00256554");
        tags.add("pda");
        tags.add("注射器");
        tags.add("口罩");
        tags.add("棉签");
        tags.add("酒精");
        tags.add("镊子");
        tags.add("牙垫");
        tags.add("1号绷带");
        return tags;
    }




    @Override
    public void onCreateViewModel() {

    }

    public void search(String key){
        setSearchWords(key);
        searchAdapter.setKeyWord(key);
           getStockList(true,ids);
    }

    public LiveData<LiveDataWrapper<List<String>>>getHistory(){

        return listLiveData;
    }

    private List<String> getLogs(List<HistoryLogResponse> historyLogResponses){
        List<String> logs = new ArrayList<>();
        if (null != historyLogResponses && !historyLogResponses.isEmpty()){
            for (HistoryLogResponse historyLogResponse : historyLogResponses){
                logs.add(historyLogResponse.getCondition());
            }
        }
        return logs;
    }

    public MediatorLiveData<LiveDataWrapper<String>> getClean() {
        return clean;
    }

    public void getHistoryLog(){
        listLiveData.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getHistory()
                .flatMap(new ResultDataParse<List<HistoryLogResponse>>())
                .compose(new RxSchedulerTransformer<List<HistoryLogResponse>>())
                .subscribe(new Consumer<List<HistoryLogResponse>>() {
                               @Override
                               public void accept(List<HistoryLogResponse> historyLogResponses) throws Exception {
                                   listLiveData.setValue(LiveDataWrapper.success(getLogs(historyLogResponses)));
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                listLiveData.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);

    }

    public void cleanHistory(){
        clean.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.cleanHistory()
                .flatMap(new ResultDataParse<String>())
                .compose(new RxSchedulerTransformer<String>())
                .subscribe(new Consumer<String>() {
                               @Override
                               public void accept(String ss) throws Exception {
                                   clean.setValue(LiveDataWrapper.success(ss));
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                clean.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);
    }
    public void handle(MaterialSearchResponse searchResponse){
//        itemclick.setValue(searchResponse);
        ARouter.getInstance()
                .build("/materialmanage/materialdetail/materiadetail")
                .withBoolean("isCanEdit",false )
                .withString("goodsCode", searchResponse.getGoodsCode())
                .navigation();

    }


}
